<?php
/*
 * 国家物流【真实用于发货的】
 */

namespace app\admin\controller\cha;

use app\admin\controller\BaseController;
use app\common\library\Tools;
use app\common\model\Channel;
use app\common\model\ExpressAttr;
use app\common\model\ExpressCountry;
use app\common\model\ExpressCountryQuotation;
use app\common\model\SysCountries;
use app\common\service\logistics\ChannelService;
use think\Db;
use think\Exception;
use think\facade\Validate;

/**
 * 国家物流管理
 * Class ExpressCountryController
 * @package app\admin\controller\cha
 */
class ExpressCountryController extends BaseController
{
    /**
     * 国家物流列表
     * @return mixed
     */
    public function index()
    {
        try{


        //页面展示
        if(!$this->request->isAjax()) {
            $this->assign("countries", SysCountries::getCodeNameCh());
            $this->assign("channel", Channel::getAll());
            $this->assign("express_country_status", ExpressCountry::$CHANNEL_STATUS);
            return $this->fetch('index');
        }
        
        //搜索查询，展示列表
        $averageAging = $this->request->post('average_aging','','intval'); //平均时效/小于
        $deliveryRate = $this->request->post('delivery_rate','','intval'); //妥投率/大于
        $countryCode = $this->request->post('country_code','','trim'); //国家
        $channelID = $this->request->post('channel_id','','trim'); //渠道
        $status = $this->request->post('status','','intval'); //状态

        //数据表模型
        $expressCountry = Db::name('express_country');
        //平均时效/小于（天）
        if($averageAging)
        {
            $expressCountry->where('average_aging', '<', $averageAging);
        }
        //妥投率/大于（%）
        if($deliveryRate)
        {
            $expressCountry->where('delivery_rate', '>', $deliveryRate);
        }
        //国家
        if($countryCode)
        {
            $expressCountry->where('country_code', $countryCode);
        }
        //渠道
        if($channelID)
        {
            $expressCountry->where('channel_id', $channelID);
        }
        //状态
        if($status)
        {
            $expressCountry->where('status', $status);
        }
        
        $expressCountries = $expressCountry->order('express_country_id desc')->paginate();
        //查询返回结果，添加字段（用each一定要return）
        $list = $expressCountries->getCollection()->each(function ($item, $key){
            $item['channel'] = Channel::getNameById($item['channel_id']);
            $item['country'] = SysCountries::getByCode($item['country_code'])->name_ch;
            return $item;
        })->toArray();
        $page = $expressCountries->render();

        $this->assign('list', $list);
        $this->assign('page', $page);
        return $this->fetch('lists');


        }catch (Exception $e){
            var_dump($e->getMessage());die;
        }


    }

    /**
     * 国家物流详情
     */
    public function info()
    {
    
        $expressCountryID= $this->request->request("express_country_id");

        //联表查询
        $expressCountry = ExpressCountry::with("quotation")->get($expressCountryID)->toArray();
        $expressCountry['channel'] = Channel::getNameById($expressCountry['channel_id']);
        $expressCountry['country'] = SysCountries::getByCode($expressCountry['country_code'])->name_ch;
        //todo 数据中的属性解析，foreach遍历
        //$this->assign("express_attr", ExpressAttr::getAll());
        
        $this->assign("express_country", $expressCountry);

        return $this->fetch("info");

        
    }

    /**
     * 新增更新国家物流【接口】
     */
    public function save()
    {


//        {
//        "__token__":"76d6b66385797c867c389df9c58e8be3",
//        "express_country.express_country_id":"3",
//        "express_country.channel_id":"20",
//        "express_country.country_code":"DE",
//        "express_country.promise_day":"7-9天",
//        "express_country.over_weight":"50元/KG",
//        "express_country.over_length":"0",
//        "express_country.remark":"若超过国家限制重量，则按该国最高重量段的价格收取运费和挂号费，且超重部分额外收取50元/KG的附加费（超重部分不足1KG按1KG计算，向上取整，允许存在50g的重量误差）。假设该国限重是30kg，但包裹是32.4kg，包裹费用: 32.4*运费 挂号费 超重重量（32.4kg-30kg-0.05kg=2.35kg，向上取整为3kg）*50",
//        "express_country.status":"1",
//        "express_country.exclude_post_code":"",
//        "quotation.start_weight":["0", "300"],
//        "quotation.end_weight":["30000", "3000"],
//        "quotation.continue_weight":["", ""],
//        "quotation.max_length":["", ""],
//        "quotation.price":["69.00", "54"],
//        "quotation.register_price":["23.00", "29"],
//        "quotation.continue_weight_price":["50.00", "50"],
//        "quotation.operation_price":["", ""],
//        "quotation.fuel_price":["", ""],
//        "quotation.customs_price":["", ""],
//        "quotation.backend_price":["", ""],
//        "quotation.tax_price":["1.00", ""],
//        "quotation.other_price":["", ""],
//        "quotation.discount":["0", ""],
//        "quotation.paobi":["", ""],
//        "quotation.status":["1", "1"],
//        "quotation.remark":["", ""],
//        "quotation.quotation_id":["3"]
//        }
        
    
         if($this->request->isPost())
        {
//                $data = $this->request->getContent();
//                // 普通验证
//                $validate = Validate::make(
//                    [
//                        'express_country.country_code'  => 'require',
//                        'express_country.channel_id'  => 'require',
//                    ],
//                    [
//                        'express_country.country_code.require' => '可走国家必填',
//                        'express_country.channel_id.require' => '渠道必填',
//                    ]
//                );
//                $data = json_decode($data,true);
//                $checkData = [
//                    'express_country' => [
//                        'country_code' => $data['express_country.country_code'],
//                        'channel_id' => $data['express_country.channel_id'],
//                    ]
//                ];
//                if(!$validate->batch()->check($checkData)) $this->error(join(', ', $validate->getError()));

            //获取复合表单提交的数据
            $json = $this->request->getContent();
            if(!Tools::isJson($json, $data)) $this->error("非法请求");
            $data = ChannelService::getInstance()->parseRequestData($data);

             ChannelService::getInstance()->addExpressCountry($data)
                 ? $this->success('操作成功')
                 : $this->error('操作失败');

        }
        else
        {
            //注：【理应把这块逻辑放到模型中处理，现应熟悉系统代码需要，先放此处】
            //只修改状态
            $validate = Validate::make([
                'express_country_id'  => 'require',
            ],[
                'express_country_id.require' => '非法请求',
            ]);
            $data = $this->request->only(['express_country_id', 'status'], 'get');
            if(!$validate->batch()->check($data))$this->error(join(', ', $validate->getError()));

            //获取更新的字段数组
            $eData = ExpressCountry::getFilterField($data, '');
            if(empty($eData)) $this->error('操作失败'); //返回操作失败
            $eData = Tools::trim($eData);

            $expressCountry = ExpressCountry::get($data['express_country_id']);
            //保存状态
            $expressCountry->save($eData) ? $this->success('操作成功') : $this->error('操作失败');

        }
        

    }

    /**
     * 新增国家物流【页面】
     */
    public function add()
    {

        try{

            $this->assign("countries", SysCountries::getCodeNameCh());
            $this->assign("channel", Channel::getAll());
            $this->assign("express_attr", ExpressAttr::getAll());
            $expressCountryID= $this->request->request("express_country_id");

            if(!empty($expressCountryID)) {
                //联表查询
                $expressCountry = ExpressCountry::with("quotation")->get($expressCountryID)->toArray();
                $expressCountry['channel'] = Channel::getNameById($expressCountry['channel_id']);
                $expressCountry['country'] = SysCountries::getByCode($expressCountry['country_code'])->name_ch;
                $this->assign("express_country", $expressCountry);
            }
            return $this->fetch("add");


        }catch (Exception $e){
            var_dump($e->getMessage());die;
        }


    }

    /**
     * 删除属性
     */
    public function delete()
    {
        $expressCountryID = $this->request->request("ids");
        if(empty($expressCountryID)) $this->error('参数错误');
        ExpressCountry::destroy($expressCountryID);
        //一并删除报价单
        ExpressCountryQuotation::destroy(['express_country_id' => $expressCountryID]);
        $this->success('删除成功');
    }
}
